package util

import (
	"io/ioutil"
	"net/http"
	"regexp"
	"strings"
)

type M3u8Info struct {
	Key    []byte
	TsUrls []string
	Iv     string
	Method string
}

// ParseM3u8File 根据m3u8文件解析出要下载的ts文件链接列表和获取解密key的url
func ParseM3u8File(srcUrl string) (info *M3u8Info, err error) {
	res, err := http.Get(srcUrl)
	if err != nil {
		return nil, err
	}
	defer res.Body.Close()
	raw, err := ioutil.ReadAll(res.Body)
	if err != nil {
		return nil, err
	}

	info = &M3u8Info{}
	lines := strings.Split(string(raw), "\n")
	keyLine := ""
	for _, line := range lines {
		if !strings.HasPrefix(line, "#") && len(line) > 0 {
			if !strings.HasPrefix(line, "https://") {
				u := res.Request.URL
				line = u.Scheme + "://" + u.Host + "/" + line
			}
			info.TsUrls = append(info.TsUrls, line)
		}
		if strings.HasPrefix(line, "#EXT-X-KEY") {
			keyLine = line
		}
	}
	if keyLine != "" {
		re := regexp.MustCompile(`URI="(.*?)"`)
		res := re.FindStringSubmatch(keyLine)
		if len(res) > 1 {
			keyUrl := res[1]
			res, err := http.Get(keyUrl)
			if err != nil {
				return nil, err
			}
			defer res.Body.Close()
			keyRaw, err := ioutil.ReadAll(res.Body)
			if err != nil {
				return nil, err
			}
			info.Key = keyRaw
		}
		re = regexp.MustCompile(`METHOD=(.*?),`)
		res = re.FindStringSubmatch(keyLine)
		if len(res) > 1 {
			info.Method = res[1]
		}
		re = regexp.MustCompile(`IV="(.*?)"`)
		res = re.FindStringSubmatch(keyLine)
		if len(res) > 1 {
			info.Iv = res[1]
		} else {
			info.Iv = string(info.Key)
		}
	}
	return info, nil
}
